<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of access_lib
 *
 * @author CTB
 */
class Accesslibrary
{
    var $kii ;
    
    //var $test;
    
    public function __construct()
    {        
        $this->ci =& get_instance();     
        $this->ci->config->load('kii_config');
        $this->kii = $this->ci->config->item('kii');        
//        $this->test['email'] = 'abcd@gmail.com';
//        $this->test['password'] = '456789';
//        $this->test['password_new'] = '123456';
//        $this->test['appName'] = 'com.kii.test3';
//        $this->test['appDesc'] = 'this is a description';
        
    }    
    function generateHash($data){
        $data = md5($data);
        $data = substr($data, 0, 15);
        return $data;
    }
    function adminAccessToken(){
        //global $kii;        
        $result = $this->login($this->kii['admin_email'], $this->kii['admin_password']);
        if($result['result']){
            return $result['response']['access_token'];
        }
        return null;
    }
    
    function sysAdminToken(){
        //global $kii;
        
        $data = array("provider_key" => $this->kii['providerkey']);
        $data_string = json_encode($data);         
        $result = $this->cloud($this->kii['get_sys_admin_token_path'], $this->kii['get_sys_admin_token_type'], $data_string, 0, null, false);
        if($result['result']){
            return $result['response']['access_token'];
            
        }
        return null;
    }
    
    function configAdminApp(){
        $token = $this->sysAdminToken();
        if($token==null){
            $result['errorMsg'] = 'Auth Admin Access Token has failed';
            $result['result'] = false;
            return $result;
        }
        $data_string = '{"emailAddressVerificationRequired" : false,"phoneNumberVerificationRequired" : false, "exposeFullUserDataToOthers":true}';  
        $bearer = 'Authorization:Bearer '.$token;
        $result = $this->cloud($this->kii['app_modification_path'], $this->kii['app_modification_type'], $data_string, 0, $bearer);    
        return $result;
    }    
    //curl -v -X POST -H "Authorization:Bearer #access_token#" 
    // -H "content-type:application/vnd.kii.AppCreationRequest+json" 
    // "http://#URL#/api/apps"
    // -d '{"appID":"enterprise", "description":"For User Management and ID Mapping", "emailAddress":"hueymeng@kii.com"}'
    
    function createApp($appId, $des, $email, $other=null){
        //global $kii;
        
        $token = $this->sysAdminToken();
        if($token==null){
            $result['errorMsg'] = 'Auth Admin Access Token has failed';
            $result['result'] = false;
            return $result;
        }
        
        $data = array("appID" => $appId, 
                      "description" => $des,
                      "emailAddress" => $email);  
        if(isset($other)){
            $data = array_merge($data, $other);
        }
        $data_string = json_encode($data);  
        $bearer = 'Authorization:Bearer '.$token;
        $result = $this->cloud($this->kii['create_app_path'], $this->kii['create_app_type'], $data_string, 0, $bearer, false);    
        if($result['result']){
            $result['response'] = array_merge($result['response'], $data);
        }
        return $result;
    }
    
    
    function createUserApp($appName, $des, $user_email, $user_token){
        
        $appId =  $this->generateHash($appName.$des); 
                
        $result = $this->createApp($appId, $des, $user_email);
        if(!$result['result']){
            return $result;
        }
        
        //Store the app info in user scope
        //global $kii;
        $data = array("appId" => $appId, "appKey" => $this->kii['appkey'], "name"=>$appName, "des"=>$des, "email"=>$user_email);        
        $data_string = json_encode($data);         
        $bearer = 'Authorization:Bearer '.$user_token;
        $result = $this->cloud($this->kii['user_app_object_path'], $this->kii['user_app_object_type'], $data_string, 0, $bearer);
        return $result;     
    }
    
    function getUserAppByName($user_token,$app_name){
        //global $kii;
        $result = $this->listUserApp($user_token);
        if($result['result']!=false){
                
                $apps = $result['response']['results'];
                foreach ($apps as &$app) {
                    if ($app['name']==$app_name)
                        return $app;
                    //echo '_id: '.$app['_id'].'| appId:'.$app['appId'].'| appKey:'.$app['appKey'].'| name:'.$app['name'].'| des:'.$app['des'];
             }
        }
        return null;
    }
    function getUserAppByObjectID($user_token,$object_id){
        //global $kii;
        $result = $this->listUserApp($user_token);
        if($result['result']!=false){
                
                $apps = $result['response']['results'];
                foreach ($apps as &$app) {
                    if ($app['_id']==$object_id)
                        return $app;
                    //echo '_id: '.$app['_id'].'| appId:'.$app['appId'].'| appKey:'.$app['appKey'].'| name:'.$app['name'].'| des:'.$app['des'];
             }
        }
        return null;
    } 
    function getUserAppByID($user_token,$app_id){
        //global $kii;
        $result = $this->listUserApp($user_token);
        if($result['result']!=false){
                
                $apps = $result['response']['results'];
                foreach ($apps as &$app) {
                    if ($app['appId']==$app_id)
                        return $app;
                    //echo '_id: '.$app['_id'].'| appId:'.$app['appId'].'| appKey:'.$app['appKey'].'| name:'.$app['name'].'| des:'.$app['des'];
             }
        }
        return null;
    } 
    function listUserApp($user_token){
        //global $kii;
        $bearer = 'Authorization:Bearer '.$user_token;
        $data_string = '{"bucketQuery":{"clause":{"type":"all"}}}';
        $result = $this->cloud($this->kii['list_user_app_object_path'], $this->kii['list_user_app_object_type'], $data_string, 0, $bearer);
        return $result;     
    }    
    
    function saveUserApp($user_token, $app){
        //global $kii;
        $bearer = 'Authorization:Bearer '.$user_token;
        $object_id = $app['_id'];
        // remove the system value if any
        unset($app['_id']);
        unset($app['_created']);
        unset($app['_modified']);
        unset($app['_owner']);
        
        $data_string = json_encode($app);
        $result = $this->cloud($this->kii['user_app_object_path'].'/'.$object_id, $this->kii['user_app_object_type'], $data_string, 1, $bearer);
    }
    
    // for additional field (e.g. url) can put in $other (e.g. $other = array("apk_url" => 'http://download/test.apk') )
    // if $result['result'] == true; $result['response'] will contain the object distributor
    function createDistributionChannel($user_token, $app, $channelName, $other=null){
        
        $appId = $app['appId'];
        $appKey = $app['appKey'];
        $email = $app['email'];
        $channelId = $this->generateHash($appId.$channelName);
        
        $bearer = 'Authorization:Bearer '.$user_token;
        $data = array("appId" => $appId, "appKey" => $this->kii['appkey'], "channelName"=>$channelName, "channelId"=>$channelId, "email"=>$email);        
        if(isset($other)){
            $data = array_merge($data, $other);
        }        
        $data_string = json_encode($data);
        
        $result = $this->cloud($this->kii['channel_object_path'], $this->kii['channel_object_type'], $data_string, 0, $bearer);
        if($result['result']){
            $result['response'] = array_merge($result['response'], $data);
        }
        return $result; 
    }
    function createFullDistributionChannel($user_token, $app, $channelName,$channelId){
        //global $kii;
        
        $appId = $app['appId'];
        $appKey = $app['appKey'];
        $email = $app['email'];
        
        $bearer = 'Authorization:Bearer '.$user_token;
        $data = array("appId" => $appId, "appKey" => $this->kii['appkey'], "channelName"=>$channelName, "channelId"=>$channelId, "email"=>$email);        
        $data_string = json_encode($data);
        
        $result = $this->cloud($this->kii['channel_object_path'], $this->kii['channel_object_type'], $data_string, 0, $bearer);
        return $result; 
    }
    
    function getDistributionChannel($channelId){
        //global $kii;
        $data_string = '{"bucketQuery":{"clause":{"type":"eq","field":"channelId","value":"'.$channelId.'"}}}';
        $result = $this->cloud($this->kii['list_channel_object_path'], $this->kii['list_channel_object_type'], $data_string);
        return $result;
    }
    function getFirstDistributionChannel($channelId){
        //global $kii;
        $data_string = '{"bucketQuery":{"clause":{"type":"eq","field":"channelId","value":"'.$channelId.'"}}}';
        $result = $this->cloud($this->kii['list_channel_object_path'], $this->kii['list_channel_object_type'], $data_string);
        if(isset($result['response']['results'][0]))
            $dis=$result['response']['results'][0];
        else
            return null;
        return $dis;
    }
    function getDistributionChannelObjectId($channelId){
        //global $kii;
        $data_string = '{"bucketQuery":{"clause":{"type":"eq","field":"channelId","value":"'.$channelId.'"}}}';
        $result = $this->cloud($this->kii['list_channel_object_path'], $this->kii['list_channel_object_type'], $data_string);
        if( $result['result'] AND sizeof($result['response']['results'])>0 ){
            $distribution = $result['response']['results'][0];
            return $distribution['_id'];
        }
        return null;
    }
    
    function deleteDistributionChannel($user_token, $channel){
        //global $kii;
        // get the real id for delete
        $bearer = 'Authorization:Bearer '.$user_token;
        $object_id = $channel['_id'];
        if(!isset($object_id)){
            $object_id = $this->getDistributionChannelObjectId($channel['channelId']);
        }
        $result = $this->cloud($this->kii['channel_object_path'].'/'.$object_id, $this->kii['channel_object_type'], null, 3, $bearer);
        return $result;
    }
    
    function saveDistributionChannel($user_token, $channel){
        //global $kii;
        
        $bearer = 'Authorization:Bearer '.$user_token;
        $object_id = $channel['_id'];
        if(!isset($object_id)){
            $object_id = $this->getDistributionChannelObjectId($channelId);
        }
        // remove the system value if any
        //unset($channel['_id']);
        //unset($channel['_created']);
        //unset($channel['_modified']);
        //unset($channel['_owner']);        
        $data_string = json_encode($channel);
        $result = $this->cloud($this->kii['channel_object_path'].'/'.$object_id, $this->kii['channel_object_type'], $data_string, 1, $bearer);
        
        return $result;
    }
    
    function listDistributionChannel($app){
        //global $kii;
        
        $appId = $app['appId'];       
        $data_string = '{"bucketQuery":{"clause":{"type":"eq","field":"appId","value":"'.$appId.'"}}}';
        $result = $this->cloud($this->kii['list_channel_object_path'], $this->kii['list_channel_object_type'], $data_string);
        return $result;     
    }
    
    
    
    
    function getShareDistributionChannelObjectId($channelId, $shareTo){
        //global $kii;
        $data_string = '{"bucketQuery":{"clause":{"type":"and","clauses":[{"type":"eq", "field":"channelId", "value":"'
                        .$channelId.
                        '"},{"type":"eq","field":"ShareTo", "value":"'.$shareTo.'"}]}}}';
        $result = $this->cloud($this->kii['list_distributor_object_path'], $this->kii['list_distributor_object_type'], $data_string);
        if( $result['result'] AND sizeof($result['response']['results'])>0 ){
            $distributor = $result['response']['results'][0];
            return $distributor['_id'];
        }
        return null;
    }
    
    function shareDistributionChannel($user_token, $channel, $shareTo){
        //global $kii;
        $channelId = $channel['channelId'];
        $bearer = 'Authorization:Bearer '.$user_token;
        $data = array("shareFrom" => $channel['email'], "shareTo" => $shareTo, "channelId"=>$channel['channelId']);        
        $data_string = json_encode($data);        
        $result = $this->cloud($this->kii['distributor_object_path'], $this->kii['distributor_object_type'], $data_string, 0, $bearer);
        return $result;        
    }
    
    function deleteShareDistributionChannel($user_token, $distributor){
        //global $kii;
        // get the real id for delete
        $bearer = 'Authorization:Bearer '.$user_token;
        $object_id = $distributor['_id'];
        if(!isset($object_id)){
            $object_id = $this->getShareDistributionChannelObjectId($distributor['channelId'],$distributor['shareTo']);
        }
        $result = $this->cloud($this->kii['distributor_object_path'].'/'.$object_id, $this->kii['distributor_object_type'], null, 3, $bearer);
        return $result;
    }
    
    function deleteShareDistributionChannelLong($user_token, $channelId,$shareTo){
        //global $kii;
        // get the real id for delete
        $bearer = 'Authorization:Bearer '.$user_token;
        //$object_id = $distributor['_id'];
        if(!isset($object_id)){
            $object_id = $this->getShareDistributionChannelObjectId($channelId,$shareTo);
        }
        $result = $this->cloud($this->kii['distributor_object_path'].'/'.$object_id, $this->kii['distributor_object_type'], null, 3, $bearer);
        return $result;
    }
    function listShareDistributionChannelByShareTo($shareTo){
        //global $kii;
        $data_string = '{"bucketQuery":{"clause":{"type":"eq","field":"shareTo","value":"'.$shareTo.'"}}}';
        $result = $this->cloud($this->kii['list_distributor_object_path'], $this->kii['list_distributor_object_type'], $data_string);
        return $result;
    }
    
     function listShareDistributionChannelByShareFrom($shareFrom){
        //global $kii;
        $data_string = '{"bucketQuery":{"clause":{"type":"eq","field":"shareFrom","value":"'.$shareFrom.'"}}}';
        $result = $this->cloud($this->kii['list_distributor_object_path'], $this->kii['list_distributor_object_type'], $data_string);
        return $result;
    }
    
    function listShareDistributionChannelByChannel($channelId){
        //global $kii;
        $data_string = '{"bucketQuery":{"clause":{"type":"eq","field":"channelId","value":"'.$channelId.'"}}}';
        $result = $this->cloud($this->kii['list_distributor_object_path'], $this->kii['list_distributor_object_type'], $data_string);
        return $result;
    }
    
    // return the list of channel info based on the given list of shareDistributionChannel
    // if the channel info is not found and $ignoreNotFound=false, null will be used
    function getDistributionChannelByShareList($listShareDistributionChannel, $ignoreNotFound=true){
        $distributions = array();
        
        foreach ($listShareDistributionChannel as &$item) {
            $channelId = $item['channelId'];
            $result = $this->getDistributionChannel($channelId);
            if($result['result']){
                if($result['response'])
                $distribution = $result['response']['results'][0];
                if(isset($distribution)){
                    array_push($distributions,$distribution);
                }else{
                    if(!$ignoreNotFound){
                        array_push($distributions,null);
                    }
                }
            }    
        }
        return $distributions;
    }
    
    /* ["userID"] - "3efdf449-ac08-462a-970a-35acefe4346c" 
       ["loginName"] - "hmtan7_1361261096" 
       ["displayName"] - "h7@kii.com" 
       ["country"] - "CN" 
       ["emailAddress"] - "h7@kii.com" 
       ["emailAddressVerified"] - true */ 
    function signup($user_email, $user_password){
        
        //global $kii;
        
        // username
        // extract the first part of the email address and append timestamp
        $email_parts = explode('@',$user_email);
        $username = $email_parts[0].'_'.time();
        
        $data = array("loginName" => $username, 
                      "emailAddress" => $user_email,
                      "displayName" => $user_email,
                      "country" => 'CN',
                      "password" => $user_password );  
    
        $data_string = json_encode($data);         
        $result = $this->cloud($this->kii['signup_path'],$this->kii['signup_type'],$data_string);
        
        if($result['result']){
            if(isset($this->kii['admin_email'])){
                $result = $this->storeUserInfo($user_email);
            }
        }
    
        return $result;
    }
    
    function storeUserInfo($email){
        //global $kii;
        $token = $this->adminAccessToken();
        if(isset($token)){
            $data = array("email" => $email);
            $data_string = json_encode($data);         
            $bearer = 'Authorization:Bearer '.$token;
            $result = $this->cloud($this->kii['user_object_path'], $this->kii['user_object_type'], $data_string, 0, $bearer);
            return $result;     
        }
        return null;
    }
    
    /* 
        ["id"] - "3efdf449-ac08-462a-970a-35acefe4346c" 
        ["access_token"] - "iNnxLFNyCZiETXkzwlwPYvO4yiZ39-gH_AskvOJQCrs"
    */  
    
    function login($user_email, $user_password)
    {
        //global $kii;
        
        $data = array("username" => $user_email, 
                      "password" => $user_password );
                      
        $data_string = json_encode($data);         
        $result = $this->cloud($this->kii['login_path'],$this->kii['login_type'],$data_string);
    
        return $result;  
    }    
    
    function changePassword($access_token, $user_password_old, $user_password_new)
    {
        //global $kii;
        
        $data = array("oldPassword" => $user_password_old, 
                      "newPassword" => $user_password_new );
                      
        $data_string = json_encode($data);         
        
        $bearer = 'Authorization:Bearer '.$access_token;
        
        $result = $this->cloud($this->kii['change_pwd_path'], $this->kii['change_pwd_type'], $data_string, 1, $bearer);
    
        return $result; 
    }
    
    function forgottenPassword($user_email){
        
        //global $kii;
        
        $path = 'apps/'.$this->kii['appid'].'/users/EMAIL:'.$user_email.'/password/request-reset'; 
        
        $result = $this->cloud($path, $this->kii['change_pwd_type'], null);
        
        return $result;
    }
    
    function checkUserExist($user_email){
        
        //global $kii;
        $token = $this->adminAccessToken();
        //$token = $this->sysAdminToken();
        if(isset($token)){
            $bearer = 'Authorization:Bearer '.$token;
            $path = 'apps/'.$this->kii['appid'].'/users/EMAIL:'.$user_email;
            $result = $this->cloud($path, null, null, 2, $bearer);
            //$result = $this->cloud($path, null, null, 2);
            return $result;     
        }
        return null;
    }
    
    // this func is only for admin use only
    function listUsers(){
        //global $kii;
        $token = $this->adminAccessToken();
        if(isset($token)){
            $bearer = 'Authorization:Bearer '.$token;
            $data_string = '{"bucketQuery":{"clause":{"type":"all"}}}';
            $result = $this->cloud($this->kii['list_user_object_path'], $this->kii['list_user_object_type'], $data_string, 0, $bearer);
            return $result;     
        }
        return null;
    }
    
    
    
    function checkAndCreateEnterpriseAppIfNotExist(){
        ////global $kii;        
        // check if the app already created
        $token = $this->adminAccessToken();
        if($token!=null){
            $result['result'] = true;
            return $result;
        }
        
        // create enterprise app
        $result = $this->createApp($this->kii['appid'], 'User Management and ID Management', $this->kii['admin_email']);
        if($result['result']==false){
            Log('error','Failed to create the Admin Applicaton');
            return $result;
        }
        
        $result = configAdminApp();
        if($result['result']==false){
            Log('error','Failed to configure the Admin Applicaton');
            return $result;
        }
        // create admin user       
       $result = $this->signup($this->kii['admin_email'], $this->kii['admin_password']);
        if($result['result']==false){
            Log('error','Failed to create Admin User'.$this->kii['admin_email']);
        }
        return $result;
    }
    

    // return the result in an array
    // $result['result'] : true mean successful else false
    // if false may refer to $result[errorMsg] for the error message
    // if true, refer to $return['response'] do the return value in array
    // $method = 0 : POST
    // $method = 1 : PUT
    // $method = 2 : GET
    function cloud($path, $type, $body, $method=0, $headerOpt=null,$app=true){
        
       //global $kii;
        
        $ch = curl_init(); 
        
        $header = array();
                        
        if($app){
            array_push($header, 'x-kii-appid: '.$this->kii['appid']);
            array_push($header, 'x-kii-appkey: '.$this->kii['appkey']);
        }                
                        
        if(isset($type)){
            array_push($header, 'content-type:'.$type);
        }
                        
        if(isset($headerOpt)){
            array_push($header, $headerOpt);
        }
        
        if(isset($body)){
            if($method==0){
                array_push($header, 'Content-Length: ' . strlen($body));
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
            }else{
                array_push($header, 'Content-Length: ' . strlen($body));
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); 
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
            }
        }else{
            
            if($method==0){
                array_push($header, 'Content-Length: 0');
                curl_setopt($ch, CURLOPT_POST, true);
            }else if($method==1){
                array_push($header, 'Content-Length: 0');
                curl_setopt($ch, CURLOPT_PUT, true);
            }else if($method==3){
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            }else{//($method==2)
                // curl_setopt($ch, CURLOPT_GET, true);
            }
        } 
                                                                                     
        curl_setopt($ch, CURLOPT_URL,  $this->kii['url'].$path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                    
                                                                          
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header );
                 
        $result = curl_exec($ch);
        
        // Check if any error occurred
        if(curl_errno($ch))
        {
            $return['errorMsg'] = 'Curl error: ' . curl_error($ch);
            $return['result'] = false;
            $return['url'] = $this->kii['url'].$path;
            
            log_message('error', 'cloud|path:'.$path);
            log_message('error', 'cloud|type:'.$type);
            log_message('error', 'cloud|body:'.$body);
            log_message('error', 'cloud|curl error:'.curl_error($ch));
        }else{
            
            $return['response'] = json_decode($result, true);
            $return['code'] = curl_getinfo($ch,CURLINFO_HTTP_CODE);
            
            if($return['code']>=200 && $return['code']<300){
                $return['result'] = true;
            }else{
                log_message('error', 'cloud|path:'.$path);
                log_message('error', 'cloud|type:'.$type);
                log_message('error', 'cloud|body:'.$body);
                log_message('error','cloud|response code:'.curl_getinfo($ch,CURLINFO_HTTP_CODE));
               
                $return['result'] = false;
                $return['url'] = $this->kii['url'].$path;
               
                if(isset($return['response']) && 
                    isset($return['response']['message'])){
                    $return['errorMsg'] = $return['response']['message'];
                }
                
                if(!isset($return['errorMsg']))
                {
                    $return['errorMsg'] = 'Invalid response code ('.$return['code'].')';
                }
                
            }
        }
        curl_close($ch);
        
        return $return;
    }    
    /*
    public function testSignUp(){
        
        //global $test;
        
        $result = $this->signup($this->test['email'], $this->test['password']);
        if($result['result']==false){
            echo 'Signed up has failed: '.$result['errorMsg'];        
        }else{
            echo var_dump($result['response']);    
        }    
    }
    
    public function testLogin(){        
        //global $test;        
        $result = $this->login($this->test['email'], $this->test['password']);
        if($result['result']==false){
            echo 'Login has failed: '.$result['errorMsg'];        
        }else{
            echo var_dump($result['response']);
            return  $result['response']['access_token'];   
        }    
    }
    
    function testChangePassword(){
        $pass = false;
        //global $test;
        
        $result = $this->login($this->test['email'], $this->test['password']);
        if($result['result']==true){
            $token = $result['response']['access_token'];
            $result = $this->changePassword($token, $this->test['password'], $this->test['password_new']);            
            if($result['result']==true){
                $result = $this->login($this->test['email'], $this->test['password_new']);
                $token = $result['response']['access_token'];            
                $result = $this->changePassword($token, $this->test['password_new'], $this->test['password']);    
                if($result['result']==true){
                    $pass = true;
                }
            }
        }
        
        if(!$pass){
            var_dump($result);
        }else{
            echo 'change password passed';
        }
    }
    
    function testForgottenPassword(){
        
        //global $test;
        
        $result = $this->forgottenPassword($this->test['email']);
        if($result['result']==false){
            echo var_dump($result);
        }else{
            echo 'Forgotten Password has passed';
        }
    }
    
    function testListUsers(){
        $result =  $this->listUsers();
        if($result['result']){
            $users = $result['response']['results'];
            foreach ($users as &$user) {
                echo $user['email']."\n";
            }
            unset($user);
        } else{ 
            echo var_dump($result);
        }
    }
    
    
    function testCreateUserApp(){
        //global $test;
        
        $result = $this->login($this->test['email'], $this->test['password']);
        if($result['result']==false){
            echo 'Login has failed: '.$result['errorMsg'];        
        }else{
            $token = $result['response']['access_token'];
            $result = $this->createUserApp($this->test['appName'], $this->test['appDesc'], $this->test['email'], $token);
            if($result['result']==false){
                echo 'testCreateUserApp has failed: '.$result['errorMsg'];    
            }else{
                echo 'testCreateUserApp has passed';
            }
            return $result;
        } 
    }
    
    function testListUserApp(){
         //global $test;
        
        $result = $this->login($this->test['email'], $this->test['password']);
        if($result['result']==false){
            echo 'Login has failed: '.$result['errorMsg'];        
        }else{
            $token = $result['response']['access_token'];
            $result = $this->listUserApp($token);
            if($result['result']==false){
                echo 'testCreateUserApp has failed: '.$result['errorMsg'];    
            }else{
                $apps = $result['response']['results'];
                foreach ($apps as &$app) {
                    print_r($app);
                    //echo '_id: '.$app['_id'].'| appId:'.$app['appId'].'| appKey:'.$app['appKey'].'| name:'.$app['name'].'| des:'.$app['des'];
                    echo "<br/>";
                }
            }
            return $result;
        } 
    }
    
    function testSaveUserApp(){
        
        //global $test;
        $result = $this->login($this->test['email'], $this->test['password']);
        
        if($result['result']==false){
            echo 'Login has failed: '.$result['errorMsg'];        
        }else{
            $token = $result['response']['access_token'];
            $result = $this->listUserApp($token);
            if($result['result']==false){
                echo 'testCreateUserApp has failed: '.$result['errorMsg'];    
            }else{
                $apps = $result['response']['results'];
                foreach ($apps as &$app) {
                    $app['des']  = $app['des'].' updated';
                    $app['addNewVariable']  = 'updated';
                    $this->saveUserApp($token,$app); 
                    
                }
            }
            return $result;
        } 
    }
    
    function printList($list){
        if(isset($list)){
        foreach ($list as &$item) {
            print_r($item);
            echo "<br/>"; 
        }
        }else{
            echo "Empty list.<br/>";
        }
    }
    
    function testDistributionChannel(){
        
        //global $test;
        
        $result = $this->login($this->test['email'], $this->test['password']);
        if($result['result']==false){
            echo 'Login has failed: '.$result['errorMsg'];        
        }else{
            $token = $result['response']['access_token'];
            $result = $this->listUserApp($token);
            if($result['result']==false){
                echo 'testCreateUserApp has failed: '.$result['errorMsg'];    
            }else{
                $apps = $result['response']['results'];
                $app = $apps[0];
                // take the first app
                $result = $this->createDistributionChannel($token, $app, 'distribution1');
                if(!$result['result']){
                    echo 'create distribution has failed';
                    echo var_dump($result);
                }else{
                    // list the distribution
                    $result = $this->listDistributionChannel($app);
                    $this->printList($result['response']['results']);
                    
                    $distribution = $result['response']['results'][0];
                    $distribution['adMediationID'] = '1223455677889';
                    $result = $this->saveDistributionChannel($token, $distribution);
                    echo var_dump($result);
                    
                    if($result['result']){
                        $result = $this->getDistributionChannelObjectId($distribution['channelId']);
                        echo 'before delete:'.$result.'<br/>';
                        $result = $this->deleteDistributionChannel($token, $distribution);
                        echo var_dump($result);
                        $result = $this->getDistributionChannelObjectId($distribution['channelId']);
                        echo '<br/>after delete:'.$result.'<br/>';
                    }
                }
            }
            return $result;
        }
    }    
*/
    
}
?>